let moment = require('moment');
const exec = require('child_process').execSync;
/*
该模块是user业务路由器：登录、注册
*/
const { Router } = require('express')
let router = new Router()
let bodyParser = require("body-parser");
//加密解密
// const {Eecrypt,Decrypt} = require('../utils/aesEncryption')
//引入用户模型
const userModel = require('../models/userModel')

router.post('/register', async (request, response) => {
  //1.获取用户的输入
  const { mail, uname, upassword, tel, gender, birthday, local } = request.body
  try {//可能会出现错误的代码放到try里面
    //3.检查该邮箱是否注册过
    let findResult = await userModel.findOne({ mail })
    if (findResult) {
      // response.send(`注册失败，${mail}该邮箱已被注册过了`)
      response.send({ success: false, message: `注册失败,${mail}邮箱已被注册` })
      return
    } else {
      await userModel.create({ mail, uname, upassword, tel, gender, birthday, local })
      response.send({ success: true, message: `注册成功`, data: findResult })
    }
  } catch (error) {
    response.send('网络不稳定，请稍后再试')
  }

})



//处理登录业务逻辑的路由
router.post('/login', async (request, response) => {
  //1.获取用户输入
  const { mail, upassword } = request.body
  try {
    let findResult = await userModel.findOne({ mail, upassword })
    if (findResult) {
      response.send({ success: true, data: findResult })
      // const token = findResult.mail
      // response.send(token)
    } else {
      response.send({ success: false, message: '登陆失败' })
    }
  }
  catch {
    response.send('网络不稳定，请稍后再试')
  }
})

//获取账户信息
router.get('/userInfo', async (req, res) => {
  const { mail } = req.query
  if (mail) {
    if (mail) {
      let userInfo = await userModel.findOne({ mail })
      if (userInfo) {
        res.send({ success: true, data: userInfo })
      } else {
        res.send({ success: false, message: '查询失败' })
      }
    }
  } else {
    let userInfo = await userModel.find()
    if (userInfo) {
      res.send({ success: true, data: userInfo })
    } else {
      res.send({ success: false, message: '查询失败' })
    }
  }

})

//修改头像
router.post('/updateProfile', bodyParser.json(), async (req, res) => {
  const { user_id, profile } = req.body
  const updateProfile = await userModel.updateOne({ 'mail': user_id }, { $set: { 'profile': profile } })
  if (updateProfile) {
    res.send({ success: true, message: '修改成功', data: updateProfile })
  } else {
    res.send({ success: false, message: '修改失败' })
  }
})


//修改账户信息
router.post('/updateUserInfo', bodyParser.json(), async (req, res) => {
  const { profile, mail, uname, tel, local, gender,upassword } = req.body;
  let params = {};
  if(profile)
    params.profile = profile;
  if(uname)
    params.uname = uname;
  if(tel)
    params.tel = tel;
  if(local)
    params.local = local;
  if(upassword)
    params.upassword = upassword;
  if(gender)
    params.gender = gender;
  const updateUserInfo = await userModel.updateOne({ mail },  params)
  if (updateUserInfo) {
    res.send({ success: true, message: '修改成功', data: updateUserInfo })
  } else {
    res.send({ success: false, message: '修改失败' })
  }
})



router.post('/updateMeInfo', bodyParser.json(), async (req, res) => {
  const { profile, mail, uname, tel, local, gender } = req.body
  const updateUserInfo = await userModel.updateOne({ mail }, { $set: { profile, mail, uname, tel, local, gender } })
  if (updateUserInfo) {
    res.send({ success: true, message: '修改成功', data: updateUserInfo })
  } else {
    res.send({ success: false, message: '修改失败' })
  }
})

//删除账号
router.post('/deleteUser', bodyParser.json(), async (req, res) => {
  const { mail } = req.body
  const deleteUser = await userModel.deleteOne({ mail })
  if (deleteUser) {
    res.send({ success: true, message: '删除成功', data: deleteUser })
  } else {
    res.send({ success: false, message: '删除失败' })
  }
})


//验证token
router.get('/verify', async (req, res) => {
  // console.log(req.headers.authorization)
  const mail = req.headers.authorization.split(' ')[1]
  //查询用户是否存在
  const user = await userModel.findOne({ mail })
  if (!user) {
    res.status(422).send('用户不存在')
  } else {
    res.send('用户存在')
  }
})


//更改状态
router.post('/updateState', bodyParser.json(), async (req, res) => {
  const { mail, state } = req.body
  const modifyState = await userModel.updateOne({ mail }, { state })
  if (modifyState) {
    res.send({ success: true, message: '更新状态成功', data: modifyState })
  } else {
    res.send({ success: false, message: '更新状态失败' })
  }
})

// 系统备份与还原
router.get('/backup', (req, res) => {
  let fileName = moment(new Date()).format('YYYY-MM-DD_HH-mm-ss');
  if (req.query.category == 1) {
    // 系统备份 
    exec(`mongodump -d adoption -o C:/dump/${fileName}`, (err, stdout, stderr) => {
      if (err) {
        res.send({
          success: false,
          msg: 'false',
        })
      }
    })
    res.send({
      success: true,
      msg: 'success',
      data: fileName
    })
  } else {
    // 系统还原  dump/2021-04-12_22-06-38
    exec(`mongorestore -d adoption C:/dump/${req.query.fileName}/adoption/`, (err, stdout, stderr) => {
      if (err) {
        res.send({
          success: false,
          msg: 'false' + err,

        })
      }
    })
    res.send({
      success: true,
      msg: 'success'
    })
  }
})

module.exports = router